package com.fangshi.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.fangshi.api.Record
import com.fangshi.api.RemoteService
import com.fangshi.pager.RecordPagingSource
import kotlinx.coroutines.flow.Flow

class RecordsViewModel(baseUrl: String) : ViewModel() {
    val allRecord: Flow<PagingData<Record>> = Pager(
        config = PagingConfig(pageSize = 20)
    ){
        RecordPagingSource(RemoteService.create(baseUrl))
    }.flow.cachedIn(viewModelScope)
}

@Suppress("UNCHECKED_CAST")
class RecordsViewModelFactory(private val remoteBaseUrl:String): ViewModelProvider.Factory{
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(RecordsViewModel::class.java)) {
            return RecordsViewModel(remoteBaseUrl) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}